<?php

namespace app\api\model;
use app\common\model\user\BalanceLog;
use app\common\model\user\BalanceLog as BalanceLogModel;
use app\common\model\user\PointsLog as PointsLogModel;
use org\Redis;
use app\common\library\wechat\WxUser;
use app\common\exception\BaseException;
use app\common\model\User as UserModel;
use app\common\model\StoreShopVisitor as StoreShopVisitorModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\dealer\Setting as DealerSettingModel;
use app\common\model\DistributionSetting as DistributionSettingModel;
use app\common\model\SingleOrder as SingleOrderModel;
use app\api\model\WxLogin as WxloginModel;
use think\Db;


/**
 * 用户模型类
 * Class User
 * @package app\api\model
 */
class User extends UserModel
{
    protected $token;

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'open_id',
        'is_delete',
        'create_time',
        'update_time'
    ];

    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
       // 记录缓存, 7天
      	$redis = new Redis();
        $openId = $redis->get($token)['openid'];

        return self::detail(['open_id' => $openId], ['address', 'addressDefault', 'grade']);
    }
    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $session = $this->wxlogin($post['code']);

        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
        $user_id = $this->register($session['openid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        // 记录缓存, 7天
      	$redis = new Redis();
        $redis->set($this->token,$session,86400 * 7);
        // Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }

    /*
     * 公众号登录
     */
    public function weixinLogin($post){
        // 获取当前小程序信息
        $wxConfig = Wxapp::getWxappCache();
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => '请到 [后台-公众号设置] 填写appid 和 appsecret']);
        }
        //微信登录(获取session_key)
        $WxUser = new WxloginModel($wxConfig['app_id'], $wxConfig['app_secret']);
        $wx=$WxUser->getAccesstoken($post['code']);
        $userInfo=$WxUser->getUserinfo($wx['access_token'],$wx['openid']);
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $user_id = $this->serregister($userInfo['openid'], $userInfo, $refereeId);
        //生成token (session3rd)
        $this->token = $this->token($userInfo['openid']);
        //记录缓存, 7天
        $redis = new Redis();
        $redis->set($this->token,$userInfo,86400 * 7);
        //Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }
    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        $wxConfig = Wxapp::getWxappCache();
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => '请到 [后台-小程序设置] 填写appid 和 appsecret']);
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);

        if (!$session = $WxUser->sessionKey($code)) {
            throw new BaseException(['msg' => $WxUser->getError()]);
        }
        return $session;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        $wxapp_id = self::$wxapp_id;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id, $data, $refereeId = null)
    {
        // 查询用户是否已存在
        $user = self::detail(['open_id' => $open_id]);

        $model = $user ?: $this;
        $this->startTrans();
        try {
            // 保存/更新用户记录
            if (!$model->allowField(true)->save(array_merge($data, [
                'open_id' => $open_id,
                'wxapp_id' => self::$wxapp_id
            ]))) {
                throw new BaseException(['msg' => '用户注册失败']);
            }
            // 记录推荐人关系
            if ($refereeId > 0 && !$user) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }
            $data = [
                'user_id'=>$model['user_id'],
                'wxapp_id'=>self::$wxapp_id,
                'visitor_num'=>1,
                'visitor_ip'=>request()->ip(),
                'create_time'=>time(),
                'update_time'=>time()
            ];
            db('store_shop_visitor')->insert($data);
            //分销商表
            $flag = db('dealer_user')->where(['user_id'=>$model['user_id'],'is_delete'=>0,'wxapp_id'=>self::$wxapp_id])->find();
            if(!$flag){
                $dealer_data = [
                    'user_id'=>$model['user_id'],
                    'wxapp_id'=>self::$wxapp_id,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                db('dealer_user')->insert($dealer_data);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return $model['user_id'];
    }

    /**
     * 公众号自动注册用户
     */
    private function serregister($open_id, $data, $refereeId = null){
        //查询用户是否已存在
        //$user = self::detail(['service_openid' => $open_id]);
        $user = self::detail(['open_id' => $open_id]);
        $model = $user ?: $this;
        $this->startTrans();
        try {
            //保存/更新用户记录
            if (!$model->allowField(true)->save(array_merge($data, [
                'nickName'=>$data['nickname'],
                'avatarUrl'=>$data['headimgurl'],
                'gender'=>$data['sex'],
                'open_id' => $open_id,
                'wxapp_id' => self::$wxapp_id
            ]))) {
                throw new BaseException(['msg' => '用户注册失败']);
            }
            //记录推荐人关系
            if ($refereeId > 0 && !$user) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }

            //分销商表
            $flag = db('dealer_user')->where(['user_id'=>$model['user_id'],'is_delete'=>0,'wxapp_id'=>self::$wxapp_id])->find();
            if(!$flag){
                $dealer_data = [
                    'user_id'=>$model['user_id'],
                    'wxapp_id'=>self::$wxapp_id,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                db('dealer_user')->insert($dealer_data);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return $model['user_id'];
    }

    /**
     * 个人中心菜单列表
     * @return array
     */
    public function getMenus()
    {
        $menus = [
            'address' => [
                'name' => '收货地址',
                'url' => 'pages/address/index',
                'icon' => 'map'
            ],
            'vip' => [
                'name' => '储值中心',
                'url' => 'pages/vip/vip',
                'icon' => 'vip'
            ],
            'coupon' => [
                'name' => '领券中心',
                'url' => 'pages/coupon/coupon',
                'icon' => 'youhuiquans'
            ],
            'my_coupon' => [
                'name' => '我的优惠券',
                'url' => 'pages/user/coupon/coupon',
                'icon' => 'youhuiquan'
            ],
            'gifts' => [
                'name' => '领取礼包',
                'url' => 'pages/gifts/gifts',
                'icon' => 'lingquan'
            ],
//            'sharing_order' => [
//                'name' => '拼团订单',
//                'url' => 'pages/sharing/order/index',
//                'icon' => 'pintuan'
//            ],
//            'my_bargain' => [
//                'name' => '我的砍价',
//                'url' => 'pages/bargain/index/index?tab=1',
//                'icon' => 'kanjia'
//            ],

            'dealer' => [
                'name' => '分销中心',
                'url' => 'pages/dealer/index/index',
                'icon' => 'fenxiaozhongxin'
            ],
            'pay_password' => [
                'name' => '支付密码',
                'url' => 'pages/password/password',
                'icon' => 'password'
            ],
            'help' => [
                'name' => '我的帮助',
                'url' => 'pages/user/help/index',
                'icon' => 'help'
            ],
        ];

        $menus['dealer']['name'] = DealerSettingModel::getDealerTitle();


        return $menus;
    }


    /**
     * 设置零钱使用
     * @param $order
     * @param $describe
     * @return mixed
     */

    public static function setBalance($orderNo,$order){

        // 新增零钱变动明细
        BalanceLog::add(20, [
            'user_id'  =>$order['user_id'],
            'money'    =>-$order['balance_money'],
            'wxapp_id' =>static::$wxapp_id,
        ], ['order_no' =>$orderNo]);

        // 更新用户可用零钱
        return self::where('user_id',$order['user_id'])->setDec('balance',$order['balance_money']);

    }


    /**
     * 判断用户是否有分销条件
     * @param $key
     * @return mixed
     */
    public function getConfigByUserType($userInfo,$type=null){

        //用户分销权限为禁用
        if($userInfo['deacler']==2) {
            $this->error = '很抱歉，您暂无推广权限';
            return false;
        }
        //获取分销方案一的配置信息
        $detail = DistributionSettingModel::getItem(1,$userInfo['wxapp_id']);
        $config = json_decode($detail['setting_content'],true);
        //分销功能未开启
        if(!$config || $config['status']==2){
            $this->error = '推广功能暂未开启';
            return false;
        }

        switch($type){
            case "gifts"://爆品礼
                if($config['hot_sale_status']==2){
                    $this->error = '推广功能暂未开启';
                    return false;
                }
                break;
            case "card"://储值卡
                if($config['card_status']==2){
                    $this->error = '推广功能暂未开启';
                    return false;
                }
                break;
            case "goods"://商品
                if($config['product_status']==2){
                    $this->error = '推广功能暂未开启';
                    return false;
                }
                break;
        }

        //用户分销权限为开启
        if($userInfo['deacler']==1) {
            return $config;
        }

        //普通用户
//        if($userInfo['shareholder']==0){
//            $this->error = '很抱歉，您暂无推广权限';
//            return false;
//        }

        //用户为微股东
//        if($userInfo['shareholder']==1){

        //分销类型 单笔
        if($config['distribution_type']==1){
            $orderInfo = SingleOrderModel::detail(
                [
                    'user_id'=>$userInfo['user_id'],
                    'wxapp_id'=>$userInfo['wxapp_id'],
                ]
            );
            if($orderInfo){
                if($orderInfo['amount']<$config['distribution_con']){
                    $this->error = '很抱歉，您暂无推广权限';
                    return false;
                }else{
                    return $config;
                }
            }else{
                if($config['distribution_con']>0){
                    $this->error = '很抱歉，您暂无推广权限';
                    return false;
                }else{
                    return $config;
                }
            }

        }
        //分销类型 累加
        if($config['distribution_type']==2){
            if($userInfo['pay_money']<$config['distribution_con']){
                $this->error = '很抱歉，您暂无推广权限';
                return false;
            }
        }
        return $config;
//        }else{
//            //获取联盟股东总配置信息  todo
//            return ['code'=>0,'data'=>[]];//联盟股东
//        }
    }


    /**
     * 获取商户的分销方案二
     * @param $key
     * @return mixed
     */
    public function getDealerTow($userInfo,$type=null){

        //获取分销方案二的配置信息
        $detail = DistributionSettingModel::getItem(2,$userInfo['wxapp_id']);
        $config = json_decode($detail['setting_content'],true);
        if(!$config) return false;
        //用户是否为代言人
        if($userInfo['is_staff']>0){

            if($config['staff'][$type]!=1) return false;
            if($config['staff']['dealer_percent']<=0 || !$config['staff']['dealer_percent']) return false;
            return $config['staff']['dealer_percent'];

        }
        //用户等级为会员
        if($userInfo['vip_level']>0){

            if($config['vip'][$type]!=1) return false;
            //根据用户等级查询对应的会员卡设置的分销比例
            $dealer_percent = db('wxapp_card')
                ->where(['card_id'=>$userInfo['vip_level'],'wxapp_id'=>$userInfo['wxapp_id']])
                ->value('reward_percent');

            if(!$dealer_percent || $dealer_percent<=0) return false;

            return $dealer_percent;

        }
        //用户等级为微股东
        if($userInfo['shareholder']==1){
            if($config['wgd'][$type]!=1) return false;
            if($config['wgd']['dealer_percent']<=0 || !$config['wgd']['dealer_percent']) return false;
            return $config['wgd']['dealer_percent'];
        }

        //用户等级为普通会员
        if($userInfo['shareholder']==0){

            if($config['common'][$type]!=1) return false;
            if($config['common']['dealer_percent']<=0 || !$config['common']['dealer_percent']) return false;
            return $config['common']['dealer_percent'];
        }


    }

}
